﻿using System.Collections.Generic;
using UnityEngine;

namespace Jinndev {

    public class DestroyCallback : MonoBehaviour {

        public static void Add(Component component, System.Action callback, string debugInfo = null) {
            Add(component.gameObject, callback, debugInfo);
        }

        public static void Add(GameObject gameObject, System.Action callback, string debugInfo = null) {
            DestroyCallback destroyCallback = gameObject.GetComponent<DestroyCallback>();
            if (destroyCallback == null) {
                destroyCallback = gameObject.AddComponent<DestroyCallback>();
            }
            destroyCallback.callback += callback;
            if (debugInfo != null) {
                destroyCallback.debugInfos.Add(debugInfo);
            }
        }

        public static void Remove(Component component, System.Action callback, string debugInfo = null) {
            Remove(component.gameObject, callback, debugInfo);
        }

        public static void Remove(GameObject gameObject, System.Action callback, string debugInfo = null) {
            DestroyCallback destroyCallback = gameObject.GetComponent<DestroyCallback>();
            if (destroyCallback == null) {
                destroyCallback = gameObject.AddComponent<DestroyCallback>();
            }
            destroyCallback.callback -= callback;
            if (debugInfo != null) {
                destroyCallback.debugInfos.Remove(debugInfo);
            }
        }

        public System.Action callback;
        public List<string> debugInfos = new List<string>();

        private void OnDestroy() {
            if (!CommonUtil.IsQuitting) {
                callback?.Invoke();
            }
        }

    }

}
